#include "filemgr.h"
#include "dbmgr.h"

#include <QStringList>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileInfoList>

using namespace std;

FileMgr::FileMgr(std::shared_ptr<DBMgr> mgr) :
    m_dbMgr(mgr)
{

}

void FileMgr::traverseFile(std::string &path)
{
    m_dbMgr->transaction();
    traverseFile(0, path);
    m_dbMgr->commit();
}

void FileMgr::traverseFile(int parent, std::string &path)
{
    QDir dir(QString::fromStdString(path));
    QStringList list;
    for (TypeInfo &typeIter : *m_supportedTypes)
    {
        QString item("*.");
        item.append(QString::fromStdString(typeIter.suffix));
        list << item;
    }

    QFileInfoList fileList = dir.entryInfoList(list, QDir::Files | QDir::NoSymLinks);
    vector<string> fullpaths;
    vector<string> basenames;
    vector<int> types;
    vector<int> isdirectorys;
    vector<int> parents;
    vector<int> thirdpartys;
    for (auto &fileIter : fileList)
    {
        QString fullpath = fileIter.absoluteFilePath();
        QString basename = fileIter.baseName();
        QString suffix = fileIter.suffix();
        int type = m_mapSuffix2id[suffix.toStdString()];

        fullpaths.push_back(fullpath.toStdString());
        basenames.push_back(basename.toStdString());
        types.push_back(type);
        isdirectorys.push_back(0);
        parents.push_back(parent);
        thirdpartys.push_back(0);
    }
    m_dbMgr->insertFiles(fullpaths, basenames, types, isdirectorys, parents, thirdpartys);

    fileList = dir.entryInfoList(list, QDir::AllDirs | QDir::NoDotAndDotDot);
    for (auto &fileIter : fileList)
    {
        QString fullpath = fileIter.absoluteFilePath();
        QString basename = fileIter.baseName();
        int type = -1;

        int dirId = m_dbMgr->insertFile(fullpath.toStdString(), basename.toStdString(), type, 1, parent, 0);
        traverseFile(dirId, fileIter.absoluteFilePath().toStdString());
    }
}

void FileMgr::setSupportedTypes(const std::shared_ptr<std::vector<TypeInfo> > &supportedTypes)
{
    m_supportedTypes = supportedTypes;
    m_mapSuffix2id.clear();
    for (TypeInfo &typeIter : *m_supportedTypes)
    {
        m_mapSuffix2id.insert({typeIter.suffix, typeIter.id});
    }
}


